package com.xxl.sso.server.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class EmailCaptchaService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${app.email.from}")
    private String fromEmail;

    @Value("${app.email.personal}")
    private String emailPersonal;

    private static final long EMAIL_CAPTCHA_EXPIRATION = 600; // 10分钟过期
    private static final String EMAIL_CAPTCHA_PREFIX = "EMAIL_CAPTCHA:";

    /**
     * 发送邮箱验证码
     * @param email 电子邮箱
     * @return 是否发送成功
     */
    public boolean sendEmailCaptcha(String email) {
        try {
            // 生成6位随机验证码
            String captcha = generateCaptcha(6);

            // 存储验证码
            redisTemplate.opsForValue().set(
                    EMAIL_CAPTCHA_PREFIX + email,
                    captcha,
                    EMAIL_CAPTCHA_EXPIRATION,
                    TimeUnit.SECONDS);

            System.out.println(redisTemplate.opsForValue().get(EMAIL_CAPTCHA_PREFIX + email));
            // 准备邮件内容
            Context context = new Context();
            context.setVariable("captcha", captcha);
            context.setVariable("expirationMinutes", EMAIL_CAPTCHA_EXPIRATION / 60);
            String emailContent = templateEngine.process("email/captcha-template", context);

            // 创建MIME邮件
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            // 设置发件人、收件人、主题和内容
            helper.setFrom(new InternetAddress(fromEmail, emailPersonal));
            helper.setTo(email);
            helper.setSubject("登录验证码");
            helper.setText(emailContent, true);

            // 发送邮件
            mailSender.send(message);
            log.info("邮箱验证码已发送至: {}", email);

            return true;
        } catch (Exception e) {
            log.error("发送邮箱验证码失败", e);
            return false;
        }
    }

    /**
     * 验证邮箱验证码
     * @param email 电子邮箱
     * @param captcha 用户输入的验证码
     * @return 是否验证成功
     */
    public boolean validateEmailCaptcha(String email, String captcha) {
        String key = EMAIL_CAPTCHA_PREFIX + email;
        String storedCaptcha = redisTemplate.opsForValue().get(key);

        if (storedCaptcha != null && storedCaptcha.equals(captcha)) {
            // 验证成功后删除验证码，防止重复使用
            redisTemplate.delete(key);
            return true;
        }

        return false;
    }

    /**
     * 生成指定长度的随机数字验证码
     */
    private String generateCaptcha(int length) {
        StringBuilder captcha = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < length; i++) {
            captcha.append(random.nextInt(10));
        }

        return captcha.toString();
    }
}
